﻿using System;
using System.Collections.Generic;
using System.Linq;
using Thuoc24h.BasePage;
using Thuoc24h.Data;
using Thuoc24h.Common;

namespace TUPA_SHOP.Views.Site
{
    public partial class AddToCartProcess : BasePages
    {
        private List<ShopCartEntity> orders;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Order"] != null)
            {
                orders = (List<ShopCartEntity>)Session["Order"];
            }
            else
            {
                orders = new List<ShopCartEntity>();
            }
            var ct = new MedLifeDataContext();
            var orderDetail = new ShopCartEntity();
            int productID = int.Parse(Page.RouteData.Values["id"].ToString());
            var product = ct.Products.FirstOrDefault(it => it.Id == productID);
            orderDetail.ID = productID;
            orderDetail.Quantity = 1;

            var unit = product.Unit;
            var unitPrice = context.PriceUnits.FirstOrDefault(it => it.Unit == unit);
            double? displayPrice = 0;
            double displayDiscountPrice = 0;
            double? displayDiscountPercent = 0;
            if (unitPrice != null)
            {
                displayDiscountPrice = (double)((unitPrice.Price / 100) * (100 - unitPrice.DiscountPercent));
                displayPrice = unitPrice.Price;
                displayDiscountPercent = unitPrice.DiscountPercent;
            }
            else
            {
                displayDiscountPrice = 0;
                displayPrice = 0;
                displayDiscountPercent = 0;
            }

            orderDetail.Price = displayPrice;
            orderDetail.ThumbImage = product.ThumbImage;
            orderDetail.Name = product.Name;

            var exits = orders.FirstOrDefault(it => it.ID == productID);
            if (exits != null)
            {
                exits.Quantity++;
            }
            else
            {
                orders.Add(orderDetail);
            }
            Session["Order"] = orders;
            Response.Redirect("~/gio-hang.aspx");
        }
    }
}